import { render, unmountComponentAtNode } from '@tarojs/react';
import { document, TaroRootElement } from '@tarojs/runtime';
import { clsx } from 'react-runtime-clsx';
import { CSSValue } from '@material/typeing';
import { ReactNode } from 'react';
import { getCurrentPages } from '@tarojs/taro';
import { isArray } from '@material/helpers';
export const getWxPages = function () {
    try {
        let currentPages = getCurrentPages();
        if (isArray(currentPages) && currentPages.length > 0) {
            const currentPage = currentPages[currentPages.length - 1];
            if (currentPage) {
                return currentPages;
            }
        }
        return [];
    } catch {
        throw new Error('没有兼容getCurrentPages方法无法获取页面栈');
    }
};

export const getCurrentPagePath = () => {
    const currentPages = getWxPages();
    const currentPage = currentPages[currentPages.length - 1]; // 获取当前页面对象
    const path = currentPage.$taroPath;
    return path || '';
};
export const getRootNode = function (rootId?: string) {
    if (rootId) {
        return document.getElementById<TaroRootElement>(rootId);
    }
    const path = getCurrentPagePath();
    if (!path) {
        return;
    }
    return document.getElementById<TaroRootElement>(path);
};

export const destroyNode = (node: any) => {
    unmountComponentAtNode(node);
    node.parentNode?.removeChild(node);
};

export type CreatNodeParams = {
    children: ReactNode;
    rootId: string;
    id: string;
    classNames?: CSSValue;
};
export const createNode = (props: CreatNodeParams) => {
    const { children, rootId = '', id, classNames } = props;
    const view = document.createElement('view');
    view.id = id;
    view.className = clsx(classNames);
    const node = getRootNode(rootId);
    if (!node) {
        return;
    }
    render(children, view, () => {
        node.appendChild(view);
    });
};
// 获取元素的高度
export const getStyleHeight = (el: HTMLDivElement | Element) => {
    if (!el) {
        return 0;
    }
    const style = window.getComputedStyle(el, null);
    const height = parseInt(style.getPropertyValue('height'), 10);
    return height || Math.floor(el.getBoundingClientRect().height);
};
